package com.atmc.controller;

import com.atmc.entity.ResponseResult;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


/**
 * @BelongsProject: SpringCloud1216
 * @BelongsPackage: com.com.atmc.controller
 * @Author: chuyings
 * @CreateTime: 2022-11-05  22:06
 * @Version: 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {
//
//    @Value("${minio.bucketName}")
//    private String bucketName;
    @Autowired
    @Qualifier("minioClient")
    MinioClient minioClient;

    @PostMapping("/upload")
    public ResponseResult uploadFile(@RequestPart("file") MultipartFile file){
        if (file == null || file.getSize() == 0) {
            return new ResponseResult(400,"上传失败");
        }

        InputStream inputStream = null;
        try {
            String bucketName = "chuyings";
            boolean exists =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
            // 不存在，创建bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                SetBucketPolicyArgs setBucketPolicyArgs=new SetBucketPolicyArgs();
//                minioClient.setBucketPolicy();
                SetBucketPolicyArgs.Builder bucket = SetBucketPolicyArgs.builder().bucket("chuyings").config("Private");
                minioClient.setBucketPolicy(setBucketPolicyArgs);
            }
            inputStream = file.getInputStream();
            minioClient.putObject(
                    PutObjectArgs
                            .builder()
                            .bucket(bucketName)
                            .object(file.getOriginalFilename())
                            .stream(inputStream,file.getSize(),-1)
                            .contentType(file.getContentType())
                            .build());

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream !=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return new ResponseResult(200,"上传成功");
    }
    @GetMapping("/download")
    public ResponseResult downLoad(){

        try {
            minioClient.downloadObject(
                    DownloadObjectArgs.builder().bucket("chuyings").object("lvbu.jpg").filename("D:\\BaiduNetdiskDownload\\minio\\lvbu.jpg").build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult(200,"下载成功");
    }
}
